最大正方形
在一个由 ‘0’ 和 ‘1’ 组成的二维矩阵内,找到只包含 ‘1’ 的最大正方形,并返回其面积。
示例:
1 2 3 4 5 6 7
| 输入: matrix = [["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"]]
输出:4
|
代码
9%98%
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Solution { public int maximalSquare(char[][] matrix) { if(matrix==null||matrix.length==0)return 0; int[][] m=new int[matrix.length][matrix[0].length]; int max=0; for(int i=0;i<matrix.length;i++) { for(int j=0;j<matrix[i].length;j++) { if(matrix[i][j]=='0'){ m[i][j]=0; continue; } int lu= (i!=0&&j!=0) ? m[i-1][j-1]:0; int left= (j!=0) ? m[i][j-1]:0; int up= (i!=0) ? m[i-1][j]:0;
m[i][j]=(Math.min(lu,Math.min(left,up))+1)*(matrix[i][j]-'0'); if(m[i][j]>max)max=m[i][j];
} } return max*max; } }
|